package cn.net.wanji.job;

import cn.net.wanji.entity.EventCar;
import cn.net.wanji.entity.EventParam;
import cn.net.wanji.entity.VehicleRsuInfo;
import cn.net.wanji.mapper.MonitorMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import static cn.net.wanji.config.CommonParamConfig.NULL_LICENSE;
import static cn.net.wanji.service.iml.DataReceiveServiceImpl.carLicense;


@Slf4j(topic = "定时处理事件列表【ServiceConfigJob】")
@EnableScheduling
@Component
public class RefreshEventTimeDataJob {

    @Autowired
    private MonitorMapper monitorMapper;

    @Value("${event.overSpeed}")
    private String overSpeed;

    @Value("${event.lowSpeed}")
    private String lowSpeed;

    @Scheduled(fixedRateString = "${event.checkTime}")
    public void updateEvent() {
        // 将数据接收处的map复制
        ConcurrentMap<String, JSONObject> cpMap = carLicense;
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取当前时间前30分钟的时间
        LocalDateTime thirtyMinutesBefore = now.minusMinutes(30);
        // 创建格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前时间和当前时间前30分钟的时间
        String now_time = now.format(formatter);
        String format_time = thirtyMinutesBefore.format(formatter);
        // 查询近半个小时的数据
        EventParam eventParam = new EventParam();
        eventParam.setStartTime(format_time);
        eventParam.setEndTime(now_time);
        List<EventCar> eventCars = monitorMapper.selectEventByEventParam(eventParam);
        HashMap<String, String> hashMap = new HashMap<>();
        for (EventCar eventCar : eventCars) {
            String plate = eventCar.getPlate();
            String eventType = eventCar.getEventType();
            hashMap.put(plate + "_" + eventType, eventCar.getRecordId());
        }
        boolean flag = eventCars.stream().map(EventCar::getPlate).anyMatch(NULL_LICENSE::equals);
        // 使用 forEach 方法遍历 map
        for (Map.Entry<String, JSONObject> entry : cpMap.entrySet()) {
            String key = entry.getKey();
            JSONObject json = entry.getValue();
            Integer vehicleSpeed = json.getInteger("vehicleSpeed");
            String recordId = json.getString("recordId");
            String type = null;
            if (vehicleSpeed > Integer.parseInt(overSpeed)) {
                type = "2";
            } else if (vehicleSpeed < Integer.parseInt(lowSpeed)) {
                type = "1";
            }
            String merge_key = key + "_" + type;
            System.out.println("Key: " + key + ", Value: " + vehicleSpeed);
            if (hashMap.containsKey(merge_key)) {
                carLicense.remove(key);
            } else {
                if (flag) {
                    if (key.length() > 10) {
                        carLicense.remove(key);
                    } else {
                        insertEventData(now_time, recordId, type);
                        carLicense.remove(key);
                    }
                } else {
                    insertEventData(now_time, recordId, type);
                    carLicense.remove(key);
                    if (key.length() > 10) {
                        flag = true;
                    }
                }
            }
        }


        /*String upGantryId = gantryFlagInfoMap.get("1");
        String downGantryId = gantryFlagInfoMap.get("2");
        // 获取当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 获取前一天的时间
        LocalDateTime previousDayDateTime = currentDateTime.minusDays(1);
        // 将时间调整为当天的0点
        LocalDateTime midnight = previousDayDateTime.withHour(0).withMinute(0).withSecond(0).withNano(0);
        // 格式化时间
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String date = midnight.format(timeFormatter);
        List<EventCar> eventCars = monitorMapper.selectFirstEventTime(upGantryId, date, "3",
                String.valueOf(Integer.parseInt(time) * 60));
        // 查询门架id为上桥门架，并且不是滞留车辆，同时开始时间和结束时间差值小于2400
        // List<EventCar> eventCars = monitorMapper.selectAllEventTime(formattedDate, String.valueOf(Integer.parseInt(time)*60));
        for (EventCar eventCar : eventCars) {
            if (upGantryId.equals(eventCar.getErId())) {
                eventCar.setUpBridgeTime(eventCar.getGantryTime());
                eventCar.setEventNumber(1);
                eventCar.setEventType("3");
                // 定义日期时间格式
                LocalDateTime currentDateTime2 = LocalDateTime.now();
                DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                // 格式化当前时间为指定格式的字符串
                String formattedDateTime = currentDateTime2.format(formatter2);
                eventCar.setTime(formattedDateTime);
                eventCar.setRecordCarId(eventCar.getRecordId() + eventCar.getCarId() + eventCar.getEventType());
                monitorMapper.insertEvent(eventCar);
            }
        }
        // 获取所有类型为3的滞留车辆，是否存在下桥时间,且下桥时间为空的下桥数据
        List<EventCar> eventDownCars = monitorMapper.selectAllDownEventByDownGantryId(downGantryId);
        for (EventCar eventDownCar : eventDownCars) {
            // 更新数据
            EventCar eventCar = monitorMapper.selectEventByCarId(eventDownCar.getCarId(), "3");
            eventCar.setDownBridgeTime(eventDownCar.getGantryTime());
            monitorMapper.insertEvent(eventCar);
        }*/

    }

    private void insertEventData(String now_time, String recordId, String type) {
        VehicleRsuInfo vehicleRsuInfo = monitorMapper.selectVehicleInfoByRecordId(recordId);
        EventCar eventCar = new EventCar();
        eventCar.setRecordCarId(vehicleRsuInfo.getRecordId() + vehicleRsuInfo.getCar_Id() + type);
        eventCar.setRecordId(vehicleRsuInfo.getRecordId());
        eventCar.setErId(vehicleRsuInfo.getErId());
        eventCar.setEventType(type);
        eventCar.setEventNumber(1);
        eventCar.setCarId(vehicleRsuInfo.getCar_Id());
        eventCar.setTime(now_time);
        eventCar.setDetectTime(vehicleRsuInfo.getDetectTime());
        eventCar.setGantryTime(vehicleRsuInfo.getDetectTime());
        eventCar.setPlate(vehicleRsuInfo.getLicenseCode());
        eventCar.setSpeed(String.valueOf(vehicleRsuInfo.getVehicleSpeed()));
        eventCar.setType(String.valueOf(vehicleRsuInfo.getIdentifyType()));
        eventCar.setHeadPic(vehicleRsuInfo.getHeadImage());
        eventCar.setSidePic(vehicleRsuInfo.getSideImage());
        eventCar.setVideo(vehicleRsuInfo.getVideo());
        monitorMapper.insertEvent(eventCar);

    }
}
